<template>
    <div class="flyer">
        <div class="headWrapper">
            <label>姓名</label>
            <el-input v-model="query.username" clearable placeholder="姓名" style="width: 100px;" class="filter-item"/>
            <label>手机号</label>
            <el-input v-model="query.phone" clearable placeholder="手机号" style="width: 140px;" class="filter-item"/>
            <!--            <label>用户账号</label>-->
            <!--            <el-input v-model="query.username" clearable placeholder="用户账号" style="width: 120px;" class="filter-item"/>-->
            <label>单位编号</label>
            <el-input v-model="query.userCode" clearable placeholder="单位编号" style="width: 100px;" class="filter-item"/>
            <!--            <label>性别</label>-->
            <!--            <el-select-->
            <!--                    v-model="query.gender"-->
            <!--                    class="filter-item"-->
            <!--                    active-color="#13ce66"-->
            <!--                    clearable-->
            <!--            >-->
            <!--                <el-option label="男" :value="1"/>-->
            <!--                <el-option label="女" :value="0"/>-->
            <!--            </el-select>-->
            <label>状态</label>
            <el-select
                    v-model="query.enabled"
                    class="filter-item"
                    active-color="#13ce66"
                    clearable
            >
                <el-option label="启用" :value="1"/>
                <el-option label="禁用" :value="0"/>
            </el-select>
            <el-button class="filter-item" type="primary" @click="onClickSearchButton">查询</el-button>
            <el-button class="filter-item" type="primary" @click="showMenu">新建</el-button>
            <el-dialog :destroy-on-close="true" :visible.sync="isShow" :title="isEdit ? '编辑飞手' : '新增飞手'" width="600px">
                <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
                    <el-form-item label="姓名" prop="username">
                        <el-input v-model="form.username" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio v-for="item in user_genders" :key="item.id" v-model="form.gender" :label="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone" maxlength="11" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="form.nickName" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="邮箱" type="email" prop="email">
                        <el-input v-model="form.email" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="单位编号" prop="userCode">
                        <el-input v-model="form.userCode" style="width: 370px;"/>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-radio v-for="item in user_status" :key="item.id" v-model="form.enabled" :label="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="text" @click="onCancelled">取消</el-button>
                    <el-button type="primary" :loading="buttonLoading" @click="formEditInfo">确认</el-button>
                </div>
            </el-dialog>
        </div>
        <el-table
                v-loading="loading"
                :data="tableData"
                style="width: 100%"
        >
            <el-table-column prop="username" label="姓名" align="center"/>
            <el-table-column prop="gender" label="性别" align="center"/>
            <el-table-column prop="phone" label="手机号" align="center"/>
            <!--            <el-table-column prop="username" label="用户账号" align="center"/>-->
            <el-table-column prop="userCode" label="单位编号" align="center"/>
            <el-table-column prop="nickName" label="昵称" align="center"/>
            <el-table-column prop="email" label="邮箱" align="center"/>
            <el-table-column prop="enabled" label="状态" align="center">
                <template slot-scope="scope">
                    {{ scope.row.enabled ? '启用' : '禁用' }}
                </template>
            </el-table-column>
            <!--            <el-table-column prop="createTime" label="创建日期" align="center"/>-->
            <el-table-column label="操作" width="200" align="center" prop="userId">
                <template slot-scope="scope">
                    <el-button type="primary" @click="onEdited(scope.row.userId)">编辑</el-button>
                    <el-button type="danger" @click="onDeleted(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page.sync="query.page"
                :page-size="10"
                layout="prev, pager, next, jumper"
                :total="totalElement"
                @current-change="handleCurrentChange"
        />
    </div>
</template>

<script>
	import {getAppUserInfo, addFlyUser, getAppUserDetailInfo, editFlyUser, deleteUserByUserId} from '@/api/user'
	import {isvalidPhone, validEmail} from '@/helper/validate'

	export default {
		name: 'Flyer',
		data() {
			const VEmail = (rules, value, cb) => {
				if (validEmail(value)) {
					cb()
				}
				cb(new Error('邮箱格式不正确'))
			}
			const VPhone = (rules, value, cb) => {
				if (isvalidPhone(value)) {
					cb()
				}
				cb(new Error('手机格式不正确'))
			}
			return {
				query: {
					username: '',
					nickName: '',
					enabled: undefined,
					page: 1,
					phone: '',
					gender: '',
					userCode: '',
					userId: '',
					size: '10'
				},
				buttonLoading: false,
				loading: false,
				rules: {
					username: [
						{required: true, message: '用户名必填', trigger: 'blur'}
					],
					nickName: [
						{required: true, message: '昵称必填', trigger: 'blur'}
					],
					phone: [
						{required: true, message: '手机号必填', trigger: 'blur'},
						{validator: VPhone, trigger: 'blur'}
					],
					userCode: [
						{required: true, message: '单位编号必填', trigger: 'blur'},
					],
					email: [
						{validator: VEmail, trigger: 'blur'}
					]
				},
				form: {
					username: '',
					nickName: '',
					phone: '',
					email: '',
					avatarName: '',
					avatarPath: '',
					password: '',
					enabled: 0,
					gender: 0,
					userId: undefined,
					userCode: ''
				},
				tableData: [],
				totalElement: 0,
				isShow: false,
				user_status: [
					{id: 0, value: false, label: '禁用'},
					{id: 1, value: true, label: '启用'}
				],
				user_genders: [
					{id: 0, value: 0, label: '男'},
					{id: 1, value: 1, label: '女'}
				],
				isEdit: false
			}
		},
		mounted() {
			this.getUserDataList()
		},
		methods: {
			async getUserDataList() {
				this.loading = true
				try {
					const {page, nickName, username, enabled, userId, gender, phone, size, userCode} = this.query
					const res = await getAppUserInfo({
						page: page - 1,
						nickName,
						username,
						enabled,
						userCode,
						userId,
						gender,
						phone,
						size
					})
					console.log(res)
					this.totalElement = res.totalElements
					this.tableData = res.content
					console.log(res)
					this.loading = false
				} catch (e) {
					console.log(e)
					this.loading = false
				}
			},
			showMenu() {
				this.isEdit = false
				this.isShow = true
				this.form = {
					username: '',
					nickName: '',
					phone: '',
					email: '',
					avatarName: '',
					avatarPath: '',
					password: '',
					enabled: true,
					gender: 0,
					userId: undefined,
					userCode: ''
				}
			},
			// 表单编辑
			formEditInfo() {
				if (this.isEdit) {
					this.$refs['form'].validate(valid => {
						if (valid) {
							this.buttonLoading = true
							this.editUserInfo()
						}
					})
				} else {
					// 新增数据
					this.$refs['form'].validate(valid => {
						if (valid) {
							this.buttonLoading = true
							this.addUserInfo()
						}
					})
				}
			},
			async addUserInfo() {
				try {
					const {email, gender, enabled, nickName, username, userCode, phone, userId} = this.form
					await addFlyUser({
						email,
						gender: gender === 1 ? '女' : '男',
						enabled,
						nickName,
						username,
						phone,
						userCode,
						userId
					})
					this.$message.success('新增人员成功')
					this.query.page = 0
					this.isShow = false
					await this.getUserDataList()
					this.buttonLoading = false
				} catch (e) {
					console.log(e)
					this.buttonLoading = false
				}
			},
			async editUserInfo() {
				try {
					await editFlyUser({
						email: this.form.email,
						gender: this.form.gender === 1 ? '女' : '男',
						enabled: this.form.enabled,
						nickName: this.form.nickName,
						username: this.form.username,
						phone: this.form.phone,
						userId: this.form.userId,
						userCode: this.form.userCode
					})
					this.$message.success('编辑成功')
					this.isShow = false
					await this.getUserDataList()
					this.buttonLoading = false
				} catch (e) {
					console.log(e)
					this.buttonLoading = false
				}
			},
			onCancelled() {
				this.isShow = false
				this.$refs['form'].clearValidate()
			},
			async onEdited(id) {
				this.isShow = true
				this.isEdit = true
				try {
					console.log(id)
					const {
						userId,
						phone,
						username,
						nickName,
						email,
						enabled,
						gender,
						userCode
					} = await getAppUserDetailInfo({
						userId: id.toString()
					})
					this.form.userId = userId
					this.form.phone = phone
					this.form.username = username
					this.form.nickName = nickName
					this.form.email = email
					this.form.enabled = enabled
					this.form.gender = gender === '男' ? 0 : 1
					this.form.userCode = userCode
				} catch (e) {
					console.log(e)
				}
			},
			onDeleted(model) {
				this.$messageBox.confirm(`此操作将永久删除${model.username}, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.deleteUser(model.userId)
					// 判断当前数据是否被页面大小整除
					if (this.tableData.length === 1) {
						// 当前页码向前移动一位
						this.query.page--
						// 重新拉取数据
						this.getUserDataList()
					}
				}).catch(() => {
					return false
				})
			},
			async deleteUser(userId) {
				try {
					await deleteUserByUserId({userId})
					this.$message.success('删除用户成功')
					await this.getUserDataList()
				} catch (e) {
					console.log(e)
				}
			},
			// 跳转页面
			async handleCurrentChange(e) {
				this.query.page = e // 修改页码
				await this.getUserDataList()
			},
			// 点击查询按钮
			async onClickSearchButton() {
				this.query.page = 1
				await this.getUserDataList()
			}
		}
	}
</script>

<style scoped lang=scss>
    @import "src/style/flyer";
</style>